package produce.jms.topic;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.jms.*;

/**
 * @author xiaohong
 * @version 1.0
 * @date 2021/11/14 0014 15:48
 * @description JMS 发布订阅模式 创建生产者
 *
 * 发布订阅模式先启动消费者订阅，然后再启动生产者去发送消息 不然会报错
 *
 */
@RequestMapping("/jms")
@RestController
public class TopicController {

    @GetMapping("/topic")
    public String jmsConsume(@RequestParam(value = "msg") String msg) throws JMSException {
//        1.创建连接工厂
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://42.193.246.110:61616");
//        2.创建连接
        Connection connection = connectionFactory.createConnection();
//        3.打开连接
        connection.start();
//        4.创建session
        /**
         * 参数一 是否开启事务
         * 参数二 消息确认机制
         */
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

//        5.创建目标地址(Queue:点对点消息，Topic:发布订阅消息>
        Topic topic = session.createTopic("top1");

//        6.创建消息生产者
        MessageProducer producer = session.createProducer(topic);

//        7.创建消息
//        createTextMessage 文本消息
        TextMessage textMessage = session.createTextMessage(msg);

//        8.发送消息
        producer.send(textMessage);

//        9.释放资源
        session.close();
        connection.close();

        return "发送消息成功：" + msg;

    }


}
